import 'package:flutter/material.dart';
import 'package:xws/helpers/safe_state.dart';
import 'package:xws/res/images.dart';
import 'package:xws/ui/root/app_root.dart';
import 'package:xws/utils/app_util.dart';
import 'package:xws/utils/storage_util.dart';
import 'package:xws/utils/theme_util.dart';
import 'package:xws/utils/tools_util.dart';
import 'package:xws/widgets/app_img.dart';
import 'package:xws/widgets/safe_scaffold.dart';

import 'guide_page.dart';

///闪屏页
class SplashPage extends StatefulWidget {
  const SplashPage({Key? key}) : super(key: key);

  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> with SafeState<SplashPage> {
  late PageController _pageController;
  Color _navColor = themeColor;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Future<void> contextReady() {
    _ready();
    return super.contextReady();
  }

  /// 初始化
  Future<void> _ready() async {
    final bool? firstRun = getV<bool>('firstRun');

    await delayed(const Duration(seconds: 1));

    if (firstRun ?? true) {
      _pageController.nextPage(
        duration: const Duration(milliseconds: 500),
        curve: Curves.ease,
      );
      setV('firstRun', false);
      safeSetState(() => _navColor = white(context));
    } else {
      push(context, const AppRoot(), remove: true, routeType: RouteType.fade);
    }
  }

  @override
  Widget build(BuildContext context) {
    initToast(context);

    return WillPopScope(
      onWillPop: () async => await exitHold(context),
      child: SafeScaffold(
        autoAppBar: false,
        systemNavigationBarColor: _navColor,
        backgroundColor: theme(context),
        body: PageView(
          physics: const NeverScrollableScrollPhysics(),
          controller: _pageController,
          children: <Widget>[
            _buildSplash,
            const GuidPage(),
          ],
        ),
      ),
    );
  }

  Widget get _buildSplash {
    return const Center(
      child: AppImg(url: R.whiteLogo, width: 62, height: 67),
    );
  }
}
